package com.titanrise.crm.handler;

import com.titanrise.crm.common.constants.SysConstant;
import com.titanrise.crm.common.enums.LogEffect;
import com.titanrise.crm.common.utils.Console;
import com.titanrise.crm.config.ThreadPoolConfig;
import com.titanrise.crm.domain.model.SysLoginLog;
import com.titanrise.crm.environment.ioc.SingletonPoolUtil;
import com.titanrise.crm.service.RootService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @Description: 处理分页逻辑
 * @Author: pront
 * @Time:2024-11-21 08:18
 */
public class ArrowKeyPagination {

    private RootService rootService;

//    FIXME 无法注入线程池
//    @Autowired
    private final ThreadPoolConfig threadPoolConfig = SingletonPoolUtil.getBean(ThreadPoolConfig.class);

    private final SharedData sharedData;
    private final int timeLine;

    public ArrowKeyPagination(SharedData sharedData, int timeLine) {
        this.sharedData = sharedData;
        this.timeLine = timeLine;
    }

    public void startPagination() {
        rootService = SingletonPoolUtil.getBean(RootService.class);

        boolean shouldUpdateLogs = true;
        while (sharedData.isRunning()) {
            try {
                // 仅当需要更新时才显示当前页数据
                if (shouldUpdateLogs) updateAndDisplayLogs();
                if (sharedData.getCurrentPage() > 1) {
                    System.out.println("上一页请输入 'u'(up)");
                }
                if (sharedData.getCurrentPage() < getTotalPages()) {
                    System.out.println("下一页请输入 'd'(down)");
                }
                System.out.println("输入 'q' 退出");
                // 监听
                shouldUpdateLogs = listenForKeyInput();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean listenForKeyInput() throws IOException {
        String input = readInputKey().toLowerCase();
        switch (input) {
            case "q":
                sharedData.stop(); // 停止分页
                return false;
            case "u":
                if (sharedData.getCurrentPage() > 1) {
                    sharedData.setCurrentPage(sharedData.getCurrentPage() - 1);
                    return true;
                } else {
                    Console.println("已经是第一页，无法再向上翻页！", LogEffect.RED, LogEffect.BOLD);
                    return false;
                }
            case "d":
                if (sharedData.getCurrentPage() < getTotalPages()) {
                    sharedData.setCurrentPage(sharedData.getCurrentPage() + 1);
                    return true;
                } else {
                    Console.println("已经是最后一页，无法再向下翻页！", LogEffect.RED, LogEffect.BOLD);
                    return false;
                }
            default:
                Console.println("无效输入！", LogEffect.RED, LogEffect.BOLD);
                return false;
        }
    }

    private String readInputKey() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        return reader.readLine().trim();
    }

    private void updateAndDisplayLogs() {
        // 更新分页数据
        List<SysLoginLog> logs = rootService.sysLoginLog(timeLine, sharedData.getCurrentPage());
        sharedData.setSysLoginLogs(logs);
        // 显示数据
        rootService.showSysLoginLogs(sharedData.getSysLoginLogs());
    }


    private int getTotalPages() {
        int totalCount = rootService.sysLoginLogCount(timeLine);
        return (int) Math.ceil((double) totalCount / SysConstant.PAGE_SIZE);
    }


    private String readArrowKey() throws IOException {
        StringBuilder input = new StringBuilder();
        while (true) {
            int ch = System.in.read();
            if (ch == 27) {
                input.append((char) ch);
            } else if (input.length() > 0 && ch == 91) {
                input.append((char) ch);
            } else if (input.length() > 0) {
                input.append((char) ch);
                break;
            } else if (ch == 'q' || ch == 'Q') {
                return "Q";
            }
        }
        return input.toString();
    }
}

